package myadmin.jtthink.com.Config;

import myadmin.jtthink.com.Filters.UserFilter;
import myadmin.jtthink.com.Mapper.MatcherAccessMapper;
import myadmin.jtthink.com.Models.MatcherAccessModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import java.util.List;

@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    UserFilter userFilter;

    @Autowired
    MatcherAccessMapper matcherAccessMapper;
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        this.setMatcherAccess(http.csrf().disable().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests()
                .antMatchers("/dept/test","/auth/**","/matcher/**").permitAll())
//                .and()
//                .authorizeRequests().antMatchers("/dept/post")
//                .access("hasRole('SYS')")
                .anyRequest().authenticated();

        http.addFilterBefore(userFilter, UsernamePasswordAuthenticationFilter.class);
    }
    private ExpressionUrlAuthorizationConfigurer<HttpSecurity>.
            ExpressionInterceptUrlRegistry setMatcherAccess(ExpressionUrlAuthorizationConfigurer<HttpSecurity>.
                                                                    ExpressionInterceptUrlRegistry expressionInterceptUrlRegistry){
        List<MatcherAccessModel> matcherAccessModels=matcherAccessMapper.selectList(null);
        for(MatcherAccessModel matcherAccessModel:matcherAccessModels){
            expressionInterceptUrlRegistry.antMatchers(matcherAccessModel.getPath())
                    .access(matcherAccessModel.getAccess());
        }
        return expressionInterceptUrlRegistry;

    }
}
